package handle

import (
	"MPCBot/global"
	"MPCBot/handle/contract"
	"MPCBot/utils/convert"
	"MPCBot/utils/ether"
	"math/big"
	"strings"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/ethclient"
)

func GetSrcDstChainIDAndExpTime(code string) (srcChainId int64, dstChainId int64, expTime int64, flag int64) {
	flagRDKey := "Flag_" + code
	codeRDStr, err := global.RD.GetString(flagRDKey)
	if err == nil && len(strings.Split(codeRDStr, "_")) == 4 {
		srcChainId = convert.MustInt64(strings.Split(codeRDStr, "_")[0])
		dstChainId = convert.MustInt64(strings.Split(codeRDStr, "_")[1])
		expTime = convert.MustInt64(strings.Split(codeRDStr, "_")[2])
		flag = convert.MustInt64(strings.Split(codeRDStr, "_")[3])
		global.Log.Info("====>  GetSrcDstChainIDAndExpTime code_[%v] srcChainId_[%v] dstChainId_[%v] expTime_[%v] flag_[%v]", code, srcChainId, dstChainId, expTime, flag)
		return
	}

	netWorkInfo := global.GetNewWorkInfo(10)
	var client *ethclient.Client
	netWorkInfo.RpcUrls, client = ether.GetEtherClient(netWorkInfo.RpcUrls)
	if len(netWorkInfo.RpcUrls) == 0 {
		global.InitNetWorkInfo()
		netWorkInfo.RpcUrls, client = ether.GetEtherClient(netWorkInfo.RpcUrls)
		if len(netWorkInfo.RpcUrls) == 0 {
			return
		}
	}
	defer client.Close()

	codeHelper, _ := contract.NewCodeHelper(common.HexToAddress(global.Conf.RunParams.CodeHelper), client)
	codeBig, _ := new(big.Int).SetString(code, 10)
	SplitCode, err := codeHelper.ChainidsAndExpTime(nil, codeBig)
	if err != nil {
		global.Log.Error("====>  ChainidsAndExpTime error：%v", err.Error())
		return
	}

	flagBig, err := codeHelper.GetFlag(nil, codeBig)
	if err != nil {
		global.Log.Error("====>  ChainidsAndExpTime error：%v", err.Error())
		return
	}

	srcChainId = SplitCode.SrcChainId.Int64()
	dstChainId = SplitCode.DstChainId.Int64()
	expTime = SplitCode.Time.Int64()
	flag = flagBig.Int64()

	codeRDStr = convert.ToString(srcChainId) + "_" + convert.ToString(dstChainId) + "_" + convert.ToString(expTime) + "_" + convert.ToString(flag)
	if _, err := global.RD.SetAndExpire(flagRDKey, codeRDStr, 3000); err != nil {
		global.Log.Error("====>  redis SetString key_[%v] codeRDStr_[%v] error：%v", flagRDKey, codeRDStr, err)
	}
	global.Log.Info("====>  redis SetString codeRDStr_[%v] success", codeRDStr)
	return
}
